package com.googlecode.c4e.ui.views;

import org.eclipse.jface.viewers.AbstractTreeViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.ui.IViewSite;
import org.eclipse.ui.model.WorkbenchContentProvider;
import org.eclipse.ui.progress.DeferredTreeContentManager;

import com.googlecode.c4e.api.model.Project;
import com.googlecode.c4e.ui.views.internal.ServersViewRoot;

public class ServersContentProvider extends WorkbenchContentProvider {

	private DeferredTreeContentManager manager;
	private ServersViewRoot root;

	public ServersContentProvider() {
		root = new ServersViewRoot();
	}

	public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
		if (viewer instanceof AbstractTreeViewer) {
			manager = new DeferredTreeContentManager(this,
					(AbstractTreeViewer) viewer);
		}
		super.inputChanged(viewer, oldInput, newInput);
	}

	public boolean hasChildren(Object element) {
		if (element == null) {
			return false;
		}

		if (element instanceof Project) {
			return false;
		}
		return true;
	}

	public Object[] getChildren(Object parentElement) {
		if (parentElement == root || parentElement instanceof IViewSite) {
			return root.getServers().toArray();
		}
		if (manager != null) {
			Object[] children = manager.getChildren(parentElement);
			if (children != null) {
				return children;
			}
		}
		return super.getChildren(parentElement);
	}
}
